package com.iot.common.config;

import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

@Configuration
public class FeignConfig {

    @Bean
    public Decoder feignDecoder() {
        return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
    }

//    @Bean
//    public RequestInterceptor requestInterceptor() {
//        return requestTemplate -> {
//            requestTemplate.header("AccessToken", TokenUtil.getToken());
//        };
//    }
    private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
        HttpMessageConverter<?> textConverter = new MappingJackson2HttpMessageConverter() {
            @Override
            public boolean canRead(Class<?> clazz, MediaType mediaType) {
                // 支持解析text/plain类型
                return mediaType.includes(MediaType.TEXT_PLAIN) || super.canRead(clazz, mediaType);
            }
        };
        return () -> new HttpMessageConverters(textConverter);
    }
}
